import * as step from '@ali/flow-step-toolkit'
import process from 'process'
import {OSSStorage} from "./oss";
import {getParams} from "./params";
import {download} from './download';
import {upload} from './upload';
import * as cache from './cache';

async function runStep(): Promise<void> {
    const params = getParams()
    if (params.cacheType == undefined) {
        params.cacheType = cache.CACHE_TYPE_OSS
    }

    let endpoint = "";
    let remoteStorage = undefined;
    switch (params.cacheType) {
        case cache.CACHE_TYPE_OSS:
            endpoint = await cache.GetEndpoint(params)
            remoteStorage = new OSSStorage({
                endpoint: endpoint,
                accessKeyID: params.accessKeyID as string,
                accessKeySecret: params.accessKeySecret as string,
                securityToken: params.securityToken,
                bucket: params.bucketName as string,
            })
    }

    if (remoteStorage == undefined) {
        throw new Error(`cache type ${params.cacheType} not support`);
    }
    step.infoV1(`ENDPOINT=${endpoint}`);

    const artifactFullName = cache.init(params)
    if (params.command == 'RUN') {
        await download(remoteStorage, params, artifactFullName)
    } else {
        await upload(remoteStorage, params, artifactFullName)
    }
}

runStep()
    .then(function () {
        step.infoV1('run cache step successfully!')
    })
    .catch(function (err: Error) {
        step.errorV1(err.message)
        process.exit(-1)
    })
